package ru.ifmo.cppsc.grammar;

import ru.ifmo.cppsc.lexer.token.Token;
import ru.ifmo.cppsc.translator.SymbolTable;
import ru.ifmo.cppsc.translator.TableRecord;
import ru.ifmo.cppsc.translator.generated.CodeContainer;

/**
 * Author: Olga Komaleva
 * Date: Jun 21, 2008
 */

public class AttributedSymbol {
    private final Symbol symbol;
    private String value;
    private int index;
    private int lineNumber;

    // for vardef token
    private String idValue;
    private String idType;

    private String type;

    SymbolTable symbolTable;


   public  AttributedSymbol(Grammar grammar, Token token, SymbolTable table) {
       symbol = grammar.getSymbolByName(token.getSymbol());
       value = token.getValue();
       index = token.getIndex();
       lineNumber = token.getLineNumber();
       symbolTable = table;

       if ( token.getVarType() != null) {
           idType = token.getVarType().getValue();
           idValue = token.getVarId().getValue();
           table.addRecord(new TableRecord(idValue, idType));
       }
       type = CodeContainer.ERROR_TYPE;

       if ( table.getRecord(value) != null ) {
           type = table.getRecord(value).getType();
       }
    }

    public AttributedSymbol(Symbol s) {
        symbol = s;
        value = null;
        index = -1;
        lineNumber = -1;
        type = CodeContainer.ERROR_TYPE;
    }

    public Symbol getSymbol() {
        return symbol;
    }

    public String getValue() {
        return value;
    }

    public int getIndex() {
        return index;
    }

    public int getLineNumber() {
        return lineNumber;
    }

    public String getIdValue() {
        return idValue;
    }

    public String getIdType() {
        return idType;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public void setIndex(int index) {
        this.index = index;
    }

    public void setLineNumber(int lineNumber) {
        this.lineNumber = lineNumber;
    }

    public String getType() {
        if (idType != null) {
            return symbolTable.getRecord(idValue).getType();
        } else {
            return type;
        }
    }

    public void setType(String type) {
        if (idType != null) {
            symbolTable.getRecord(value).setType(type);
        } else {
            this.type = type;
        }
    }
}
